package com.xw.Mail.Parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.activation.DataSource;
import javax.mail.MessagingException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.mail.util.MimeMessageParser;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.xw.Utils.DateUtil;
import com.xw.Utils.StrUtil;

/**
 * 邮件HTML图片标签解析器
 * 
 * @author YangJianquan
 */
@Component
public class HtmlParse {
	
	private static final String IMAGE_FOLDNAME = "mailImages";
	Logger logger = LoggerFactory.getLogger(HtmlParse.class);
	
	//上传文件的根目录
	@Value("${upload.file.rootPath}")
	private String uploadRootPath;
	//上传文件的文件夹名
	@Value("${upload.file.rootFolderName}")
	private String uploadRootFolderName;
	//文件服务器根路径
	@Value("${upload.fileServer.rootUrl}")
	private String fileServerUrl;
	
	/**
	 * 解析html中的img标签，下载图片，然后将src替换成本地的
	 * @param html 待解析的html标签
	 * @return
	 */
	public String parseImgSrc(String html, String from, MimeMessageParser parser){
		if (StringUtils.isEmpty(html)) {
			return "";
		}
		Document doc = Jsoup.parse(html);
		try {
			String mailName = parser.getMimeMessage().getFolder().getURLName().getUsername();
			Elements elements = doc.select("img");
			for (Element element : elements) {
				logger.info(element.toString());
				String src = element.attr("src");
				if (StringUtils.isEmpty(src)) {
					continue;
				}
				String imagePath = src;
				try {
					if (src.contains("cid:")) {
						// 图片在附件中
						String url = parseCidImg(parser,mailName, src);
						element.attr("src", url);
					} else if (src.contains("base64,")) {
						// base64的url就不解析
						element.attr("src", imagePath);
					} else {
						// 非base64的url,非cid的图片
						String url = parseImgFromUrl(src,mailName);
						element.attr("src", url);
					}
				} catch (IOException e) {
					logger.error("解析邮件中的图片发生异常！", e);
				}
			}
		} catch (MessagingException e) {
			logger.error("获取邮箱名称发发生异常！", e);
		}
		return doc.toString();
	}

	/**
	 * 描述：下载src的图片，保存到文件服务器，返回url地址
	 * @author 杨建全
	 * @date 2017年6月7日
	 * @param src
	 * @param mailName
	 * @return
	 * @throws IOException 
	 */
	private String parseImgFromUrl(String src, String mailName) throws IOException {
		URL url = new URL(src);
		InputStream is = url.openStream();
		//生成文件名
		String fileName = StrUtil.uuidWithodHyphen()+"_"+StrUtil.getFileType(src);
		//生成图片url地址
		String ret = fileServerUrl+"/"+uploadRootFolderName+"/"+IMAGE_FOLDNAME + "/" + DateUtil.getTodayStr() + "/" + fileName;
		FileOutputStream outStream = null;
		try {
			// 获取邮箱名，用于存储文件
			String fileFolderName = uploadRootPath+File.separator+uploadRootFolderName + File.separator + IMAGE_FOLDNAME + File.separator + DateUtil.getTodayStr();
			File folder = new File(fileFolderName);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			String fileRealPath = fileFolderName + File.separator + fileName;
			outStream = new FileOutputStream(fileRealPath);
			IOUtils.copy(is, outStream);
		} finally {
			if (is!=null) {
				is.close();
			}
			if (outStream != null) {
				outStream.close();
			}
		}
		return ret;
	}

	/**
	 * @param parser 邮件解析对象
	 * @param path  附件保存路径
	 * @param mailName  邮箱名
	 * @param src 图片标签src
	 * @return
	 */
	private String parseCidImg(MimeMessageParser parser,String mailName, String src) throws FileNotFoundException, IOException {
		String[] cids = src.split(":");
		String cid = "";
		if (null != cids && cids.length == 2) {
			cid = cids[1];
		}
		DataSource ds = parser.findAttachmentByCid(cid);
		if (null == ds) {
			return "";
		}
		String dsName = ds.getName();
		String fileName = "";
		if (dsName.contains("/")) {
			fileName = StrUtil.uuidWithodHyphen() + "." +StrUtil.getFileType(dsName);
		}else{
			fileName = StrUtil.uuidWithodHyphen() + "_" + dsName;
		}
		
		String ret = fileServerUrl+"/"+uploadRootFolderName+"/"+IMAGE_FOLDNAME + "/" + DateUtil.getTodayStr() + "/" + fileName;
		FileOutputStream outStream = null;
		try {
			// 获取邮箱名，用于存储文件
			String fileFolderName = uploadRootPath+File.separator+uploadRootFolderName + File.separator + IMAGE_FOLDNAME + File.separator + DateUtil.getTodayStr();
			File folder = new File(fileFolderName);
			if (!folder.exists()) {
				folder.mkdirs();
			}
			String fileRealPath = fileFolderName + File.separator + fileName;
			outStream = new FileOutputStream(fileRealPath);
			IOUtils.copy(ds.getInputStream(), outStream);
		} finally {
			if (outStream != null) {
				outStream.close();
			}
		}
		return ret;
	}

	/**
	 * 根据传入参数选着解析方法
	 * @param htmlContent
	 * @param from
	 * @param parser
	 * @return
	 */
	public String parse(String htmlContent, String from, MimeMessageParser parser) {
		return parseImgSrc(htmlContent, from, parser);
	}
	
	
	

}
